package xpn.platform.modules.sys.role;

import lombok.Getter;
import lombok.Setter;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.rest.core.annotation.RestResource;
import xpn.platform.common.persistence.AbstractBaseEntity;
import xpn.platform.modules.sys.user.SysUser;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;

@Entity
@Getter
@Setter
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" }, ignoreUnknown = true)
public class SysRole extends AbstractBaseEntity {
	private static final long serialVersionUID = -5480282680329657469L;

	@Column(unique = true, length = 100)
	@Length(min = 2, max = 40)
	@NotEmpty
	private String name;

	@Column(nullable = false)
	private Float sortNo; // 排序号

	@Column(length = 128)
	@Length(min=0, max = 128)
	private String description;

	// 包含的用户
	@ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY)
	@JsonIgnore
	@RestResource(exported = false)
	private Set<SysUser> users = new HashSet<SysUser>();

	// 获取关联属性
	// 获取包含的用户列表
	@JsonIgnore
	public Set<String> fetchUserList() {
		Set<String> userList = new HashSet<String>();
		if (this.getUsers() == null) {
			return userList;
		}
		for (SysUser user : this.getUsers()) {
			userList.add(user.getName());
		}
		return userList;
	}
}